// src/services/weatherService.js (Final Hybrid Version)

import AMapLoader from '@amap/amap-jsapi-loader';
import { A_MAP_KEY, A_MAP_SECURITY_KEY } from '../config/amap.js';

const weatherService = {
    /**
     * 获取当前天气。
     * 优先尝试高精度定位，如果失败则自动降级到IP定位。
     */
    async getCurrentWeather() {
        try {
            window._AMapSecurityConfig = {
                securityJsCode: A_MAP_SECURITY_KEY,
            };

            // 一次性加载所有需要的插件
            const AMap = await AMapLoader.load({
                key: A_MAP_KEY,
                version: "2.0",
                plugins: ['AMap.Geolocation', 'AMap.CitySearch', 'AMap.Weather'],
            });

            // 封装一个获取高精度定位的Promise
            const getCityByGeolocation = () => {
                return new Promise((resolve, reject) => {
                    const geolocation = new AMap.Geolocation({
                        enableHighAccuracy: true,
                        timeout: 8000, // 设置8秒超时
                        needAddress: true,
                    });
                    geolocation.getCurrentPosition((status, result) => {
                        if (status === 'complete' && result.info === 'SUCCESS' && result.addressComponent && result.addressComponent.city) {
                            console.log('高精度定位成功:', result.addressComponent.city);
                            resolve(result.addressComponent.city);
                        } else {
                            reject(new Error('高精度定位失败'));
                        }
                    });
                });
            };

            // 封装一个获取IP定位的Promise作为备用方案
            const getCityByIP = () => {
                return new Promise((resolve, reject) => {
                    const citySearch = new AMap.CitySearch();
                    citySearch.getLocalCity((status, result) => {
                        if (status === 'complete' && result.info === 'OK' && result.city) {
                            console.warn('高精度定位失败，已自动降级到IP定位:', result.city);
                            resolve(result.city);
                        } else {
                            reject(new Error('IP定位也失败了'));
                        }
                    });
                });
            };

            // 核心逻辑: 尝试高精度，如果捕获到任何错误，就执行IP定位
            const cityName = await getCityByGeolocation().catch(getCityByIP);

            // 最终，使用获取到的城市名称查询天气
            return new Promise((resolve, reject) => {
                const weather = new AMap.Weather();
                weather.getLive(cityName, (err, data) => {
                    if (!err && data) {
                        resolve(data);
                    } else {
                        reject(new Error(`获取 [${cityName}] 的天气失败`));
                    }
                });
            });

        } catch (e) {
            console.error("天气服务初始化失败:", e);
            throw e; // 将最终错误抛给UI组件去处理
        }
    },
};

export default weatherService;